package jdh.util.db.transacao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class EntityManagerInterceptador extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	private String result;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		if (this.validarLogin()) {
			try {
				System.out.println("Abriu");
				JPAUtil.getIntance().beginTransaction();
				this.result = invocation.invoke();
				JPAUtil.getIntance().commitTransaction();
				System.out.println("COMMIT");
			} catch (Exception e) {
				e.printStackTrace();
				JPAUtil.getIntance().rollbackTransaction();
				System.out.println("ROLLBACK");
			} finally {
				System.out.println("Retorno: " + this.result);
				JPAUtil.getIntance().closeEntityManager();
			}
		}
		return this.result;
	}

	private final boolean validarLogin() {
		boolean isLogado = false;
		if (!ActionContext.getContext().getSession().containsKey("isLogado")) {
			this.result = "erroLogin";
		} else {
			isLogado = (Boolean) ActionContext.getContext().getSession()
					.get("isLogado");
			if (!isLogado) {
				this.result = "erroLogin";
			} else {
				System.out.println((Boolean) ActionContext.getContext()
						.getSession().get("isLogado"));
			}
		}
		return true;
	}
}
